﻿#region Copyright(C) 2018 FI Ltd. All rights reserved.
// ==================================================================================================
// Copyright(C) 2018 FI Ltd. All rights reserved.
//
// SYSTEM NAME	    : FI.Net Application Framework
// COMPONENT ID	    : FI.Core
// COMPONENT DESC   : The foundation component of the whole framework. 	
//
// CREATED DATE/BY  : 18 Aug 2018 / Tian Mi
//
// REVISION HISTORY :	
// DATE/BY			SR#/CS/PM#/OTHERS		DESCRIPTION OF CHANGE
// ==================================================================================================
#endregion
using FI.Core.Properties;
using FI.Core.Utilities;
using System;
using System.ComponentModel;

namespace FI.Core
{
    /// <summary>
    /// This class defines some extension method for type conversion.
    /// </summary>
    public static class TypeConversionExtension
    {
        /// <summary>
        /// Converts the given type to the specified type.
        /// </summary>
        /// <param name="value">The value to be converted.</param>
        /// <param name="conversionType">Type of the conversion.</param>
        /// <returns>The casted object.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Convert.ChangeType(System.Object,System.Type)")]
        public static object ConvertTo(this object value, Type conversionType)
        {
            Guard.ArgumentNotNull(value, "value");
            Guard.ArgumentNotNull(conversionType, "targetType");
            if (null == value)
            {
                return null;
            }
            if (!conversionType.IsGenericType)
            {
                return Convert.ChangeType(value, conversionType);
            }

            if (conversionType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                return new NullableConverter(conversionType).ConvertFrom(value);
            }

            throw new InvalidCastException(
                ResourceUtility.Format(Resources.ExceptionInvalidCast, value.GetType().FullName, conversionType.FullName));

        }
    }
}
